package com.knowledgeqa.system.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import com.knowledgeqa.system.common.Result;
import com.knowledgeqa.system.common.ResultCode;

/**
 * 全局异常处理器
 * 统一处理系统中的所有异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseEntity<Result<?>> handleBusinessException(BusinessException ex, WebRequest request) {
        logger.error("业务异常: {}", ex.getMessage(), ex);
        Result<?> result = new Result<>(ex.getCode(), ex.getMessage(), null);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ResponseEntity<Result<?>> handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) {
        logger.error("参数异常: {}", ex.getMessage(), ex);
        Result<?> result = new Result<>(ResultCode.PARAM_ERROR.getCode(), ex.getMessage(), null);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理未授权异常
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public ResponseEntity<Result<?>> handleUnauthorizedException(UnauthorizedException ex, WebRequest request) {
        logger.error("未授权异常: {}", ex.getMessage(), ex);
        Result<?> result = new Result<>(ResultCode.UNAUTHORIZED.getCode(), ex.getMessage(), null);
        return new ResponseEntity<>(result, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(ForbiddenException.class)
    @ResponseBody
    public ResponseEntity<Result<?>> handleForbiddenException(ForbiddenException ex, WebRequest request) {
        logger.error("权限不足异常: {}", ex.getMessage(), ex);
        Result<?> result = new Result<>(ResultCode.FORBIDDEN.getCode(), ex.getMessage(), null);
        return new ResponseEntity<>(result, HttpStatus.FORBIDDEN);
    }

    /**
     * 处理服务器内部异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Result<?>> handleException(Exception ex, WebRequest request) {
        logger.error("系统异常: {}", ex.getMessage(), ex);
        Result<?> result = new Result<>(ResultCode.SYSTEM_ERROR.getCode(), "系统内部错误，请稍后再试", null);
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}